//termio_control_test.cpp
//Erik Wright
/*
This program is intended to be a test program 
to test the settings of the lynxmotion SSC-32
for it's RS232 connection. 

This file uses the POSIX termios.h library and 
was compiled and tested on an ubuntu 12.04 
system.
*/



#include <termios.h>
#include <iostream>	//standard input output
#include <fcntl.h>	//file input output 
#include <stdio.h>

using namespace std;

#define BAUDRATE B115200
#define DEVICE "/dev/ttyUSB0"


int main()
{
	termios new_termios;
	termios old_termios;
	int fd;		//file descriptor for terminal stream
	int retval;	//return value indicating error or success

	//open the usb to RS232 connector 	
	fd = open(DEVICE, O_NOCTTY);
	if(fd < 0)
	{
		cout<<"ERROR: File descriptor is less than zero"<<endl;
		cout<<"FD = "<<fd<<endl;
		return 0;	//break execution
	}
	else
	{
		cout<<"Device: "<<DEVICE<<" has opened with file descriptor "<<fd<<endl;
	}


	//get the current terminal configurations
	retval = tcgetattr(fd, &old_termios);
	if(retval < 0)
	{
		cout<<"ERROR: Could not get the current terminal configuration."<<endl;
		return 0;	//break execution
	}

	
	/*
	Set the terminal settings for the SSC-32.  Here we want
	to use settings for:
		/dev/ttyUSB0 as intended device
		115200 Baud connection
		8 data bits
		One stop bit
		No Parity
		No flow control
	*/
//	new_termios.c_iflag = //input modes

	/*
		ONLRET:	NL performs CR function
	*/
	new_termios.c_oflag = ONLRET; 
	new_termios.c_cflag = CS8;	//8 data bits

	cfsetospeed(&new_termios, BAUDRATE);	//set baud rate output
	cfsetispeed(&new_termios, BAUDRATE);	//set input baud rate
		
	retval = tcsetattr(fd, TCSAFLUSH, &new_termios);	//give the new port settings
	if(retval < 0)
	{
		cout<<"ERROR: Could not set the new terminal configuration."<<endl;
		return 0;	//terminate program
	}



	retval = write(fd,"#0 P1700 T1000\r",15);
	if(retval < 0)
	{
		cout<<"ERROR: Could not send character string to controller."<<endl;
		cout<<"ERROR NUM: "<<retval<<endl;
		cout<<endl;
	}


/*
	bool done = 0;

	while(!done)
	{
		
	
		done = 1;	
	}
*/
	
	cout<<"Closing Open File Descriptor"<<endl;

	//close the open terminal device
	retval = tcsetattr(fd, TCSAFLUSH, &old_termios);	//reset the old values
	close(fd);

	return 1;
}
